package com.wocao.service.impl;


import com.wocao.entity.ReqBody;
import com.wocao.entity.SysDept;
import com.wocao.mapper.SysDeptMapper;
import com.wocao.service.SysDeptService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wocao.utils.Tree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 部门表 服务实现类
 * </p>
 *
 * @since 2023-11-21
 */
@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService {
    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Override
    public List<Long> selectDeptIdsByRoleId(long roleId) {
        return sysDeptMapper.selectDeptIdsByRoleId(roleId);
    }

    @Override
    public List<SysDept> selectDeptAll(ReqBody reqBody) {
        List<SysDept> sysDepts = sysDeptMapper.selectDeptAll(reqBody.getDeptName(), reqBody.getStatus());
//        ArrayList<SysDept> qwe = new ArrayList<SysDept>();
//        long parId = 0L;
//        for (int i = 0; i < sysDepts.size(); i++) {
//            if (sysDepts.get(i).getParentId()!=parId){
//                parId=sysDepts.get(0).getParentId();
//                List<SysDept> list = Tree.deptTree(sysDepts, parId);
//                qwe.add(list.get(0));
//            }else {
//                List<SysDept> deptList = Tree.deptTree(sysDepts, sysDepts.get(0).getParentId());
//                return deptList;
//            }
//        }
        List<SysDept> deptList = Tree.deptTree(sysDepts, sysDepts.get(0).getParentId());
        return deptList;
    }

    @Override
    public void deptAdd(SysDept dept) {
        //部门有两个添加，主添加是无法直接获取它的祖级列表
        if (dept.getAncestors()==null || dept.getAncestors()==""){
            SysDept sysDept = sysDeptMapper.selectById(dept.getParentId());
            dept.setAncestors(sysDept.getAncestors()+","+sysDept.getDeptId());
        }
        sysDeptMapper.insert(dept);
    }

    @Override
    public void deptEdit(SysDept dept) {
        //修改，同父级id获取父级的祖级列表
        if (dept.getAncestors()==null || dept.getAncestors()==""){
            SysDept sysDept = sysDeptMapper.selectById(dept.getParentId());
            dept.setAncestors(sysDept.getAncestors()+","+sysDept.getDeptId());
        }
        sysDeptMapper.updateById(dept);
    }

    @Override
    public void deleteDept(long deptId) {
        sysDeptMapper.deleteDept(deptId);
    }

    @Override
    public String selectChildDept(long deptId) {
        List<SysDept> deptList = sysDeptMapper.selectChildDept(deptId);
        if (deptList.size()==0){    //条数=0，说明没有未停用的子部门，可以修改当前部门状态
            return "ok";
        }else {
            return "no";
        }
    }

    @Override
    public String selectFatherDept(long parentId) {
        SysDept sysDept = sysDeptMapper.selectFatherDept(parentId);
        if (sysDept==null){
            return "ok";
        }else {
            return "no";
        }

    }
}
